import {getUserByName} from "../service/user.js";
import response from "../utils/response.js";
import {md5password} from "../utils/index.js";
import NetCode from "../constants/NetCode.js";

/**
 * 校验用户名和密码不能为空
 * @param ctx
 * @param next
 * @returns {Promise<{code: number, message: *, timestamp: number}|{code: number, data: *, message: *, timestamp: number}>}
 */
export async function verifyUser(ctx, next) {
    const {username, password} = ctx.request.body
    if(!username || !password){
        ctx.body = response(NetCode.ERROR,null,'用户名或密码不能为空');
        return ;
    }
    await next()
}

/**
 * 校验用户是否已经注册
 * @param ctx
 * @param next
 * @returns {Promise<{code: number, message: *, timestamp: number}|{code: number, data: *, message: *, timestamp: number}>}
 */
export async function alreadyUser(ctx, next){
    const {username} = ctx.request.body
    const users = await getUserByName(username)
    if(users.length){
        ctx.body = response(NetCode.ERROR, null, `用户已经存在`)
    } else {
        await next()
    }
}


/**
 * 密码加密
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 */
export async function handlePassword(ctx, next){
    const {password} = ctx.request.body
    ctx.request.body.password = md5password(password)
    await next()
}